import * as VueRouter from "vue-router";
import _ from "lodash";
import {
  AppRoute,
  CustomRouterOptions,
  defaultCustomRouterOptions,
  defaultVueRouterOptions,
  VueRouterOptions
} from "./app-router-type";
import afterNavigation from "./after-navigation";
import beforeNavigation from "./before-navigation";
import AppRouterUtil from "./app-router-util";

// ################ API ####################
export const createRouter = (
    options: VueRouterOptions,
    extraOptions?: CustomRouterOptions
) => {
  // 转换为VueRoutes
  const routerOptions = _.defaultsDeep(options, defaultVueRouterOptions);
  routerOptions.routes = AppRouterUtil.convertToVueRoutes(routerOptions.routes);

  // 创建VueRouter
  const router = VueRouter.createRouter(routerOptions);

  // 处理AppRouter自定义选项
  const customRouterOptions = extraOptions
      ? _.defaultsDeep(extraOptions, defaultCustomRouterOptions)
      : defaultCustomRouterOptions;

  router.beforeEach(async (to, from) => {
    return await beforeNavigation(to, from, customRouterOptions);
  });

  router.afterEach((to, from, failure) => {
    afterNavigation(to, from, customRouterOptions, failure);
  });
  return router;
};

export function defineRoute<META>(route: AppRoute<META>): AppRoute<META> {
  return route;
}